// 网络请求封装
import store from '@/store'
import { md5 } from 'js-md5';

// 基础配置
const config = {
  baseURL: process.env.NODE_ENV === 'development'
    ? '/api'
    : 'http://192.168.0.102:8090/data',
  timeout: 10000,
  header: {
    'Content-Type': 'application/json'
  }
}

// 请求拦截器
const requestInterceptor = (options) => {
  // 添加token到请求头
  const token = store.getters['auth/token']
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': `Bearer ${token}`
    }
  }
  const Authorization = uni.getStorageSync('userInfo')?.sessionid;
  if (Authorization && options.url == '/voucher/list') {
    let json = JSON.stringify(options.data.data);
    options.data.md5key = md5(json + "|" + uni.getStorageSync("secretkey"));
    options.data.sessionid = Authorization;
    options.data.data = json;
  }

  // 添加基础URL
  if (!options.url.startsWith('http')) {
    options.url = config.baseURL + options.url
  }

  // 设置超时时间
  options.timeout = options.timeout || config.timeout

  return options
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response

  // 请求成功
  if (statusCode >= 200 && statusCode < 300) {
    return data
  }

  // 处理特定错误码
  switch (statusCode) {
    case 401:
      // 未授权，清除登录状态并跳转到登录页
      store.dispatch('auth/logout')
      uni.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none'
      })
      break
    case 403:
      uni.showToast({
        title: '没有权限访问',
        icon: 'none'
      })
      break
    case 404:
      uni.showToast({
        title: '请求的资源不存在',
        icon: 'none'
      })
      break
    case 500:
      uni.showToast({
        title: '服务器内部错误',
        icon: 'none'
      })
      break
    default:
      uni.showToast({
        title: '网络请求失败',
        icon: 'none'
      })
  }

  return Promise.reject(response)
}

// 请求方法封装
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 应用请求拦截器
    const interceptedOptions = requestInterceptor(options)

    uni.request({
      ...interceptedOptions,
      success: (response) => {
        try {
          const result = responseInterceptor(response)
          result.data = JSON.parse(result.data, function (key, value) {
            if (typeof value === 'string' && !isNaN(value)) {
              return Number(value);
            }
            return value;
          });
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

// 便捷方法
const http = {
  get(url, data = {}, options = {}) {
    return request({
      url,
      method: 'GET',
      data,
      ...options
    })
  },

  post(url, data = {}, options = {}) {
    return request({
      url,
      method: 'POST',
      data,
      ...options
    })
  },

  put(url, data = {}, options = {}) {
    return request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  },

  delete(url, data = {}, options = {}) {
    return request({
      url,
      method: 'DELETE',
      data,
      ...options
    })
  },

  upload(url, filePath, options = {}) {
    return new Promise((resolve, reject) => {
      const token = store.getters['auth/token']
      const header = token ? { 'Authorization': `Bearer ${token}` } : {}

      uni.uploadFile({
        url: config.baseURL + url,
        filePath,
        name: 'file',
        header,
        ...options,
        success: (response) => {
          try {
            const data = JSON.parse(response.data)
            resolve(data)
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  }
}

export default http 